package gitobject;
import repository.Repository;
import zlib.ZLibUtils;


import java.io.*;

import java.nio.file.Files;
import java.nio.file.Paths;


public class GitObject implements Serializable{

    protected String fmt;                  //type of object  // blob/tree/commit
    protected String key;                  //key of object
    protected String mode;                 //mode of object  // 100644/040000/NA
    protected static String path = Repository.getGitDir() + File.separator + "objects";          //absolute path of objects
    protected String value;                //value of object

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }


    public GitObject(){}
    /**
     * Get the value(content) of file
     * @param file
     * @return String
     * @throws IOException
     */
    public static String getValue(File file) throws IOException {
        /* Add your code here -- DONE --TESTED*/
        byte[] encoded = Files.readAllBytes(Paths.get(file.getCanonicalPath()));
        return new String(encoded);
    }

    /**
     * 序列化方法
     * Serialize the object to the local repository.
     * @throws Exception
     */
    public void writeObject() throws Exception{
        String curPath = path + File.separator + key.substring(0, 2) + File.separator + key.substring(2);
        File outFile = new File(curPath);
        outFile.getParentFile().mkdirs(); // 创建父级文件夹
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFile, false));
        out.writeObject(this);
        out.close();
    }

    /**
     * 序列化方法+压缩
     * Serialize the object and compress with zlib.
     * @throws Exception
     */
    public void compressWrite() throws Exception{
        String curPath = path + File.separator + key.substring(0, 2) + File.separator + key.substring(2);
        File outFile = new File(curPath);
        if (outFile.exists()) {
//            System.out.println("already exist");
//            System.out.println("----------------------");
            return; // 若同key对象已存在，则不再重复添加
        }
        outFile.getParentFile().mkdirs(); // 创建父级文件夹
        FileOutputStream fos = new FileOutputStream(outFile);
        // 序列化
        ObjectOutputStream out = new ObjectOutputStream(fos);
        out.writeObject(this);
        fos.close();
        out.close();

        // 进行压缩：首先读入
        File inFile = new File(curPath);
        // 转为字节流进行压缩
        byte[] data = ZLibUtils.compress(Files.readAllBytes(inFile.toPath()));
        // 将压缩文件写入
        fos = new FileOutputStream(outFile);
        ZLibUtils.compress(data, fos);
        fos.close();
//        System.out.println(this.getFmt() + " written to ./object!");
//        System.out.println("----------------------");
    }

}
